/**
*@author Bruno Fagundez @ 6-9-2008
*/
public class DiscussionMembersWidgetController {
	
	private DiscussionForum__c discussion = new  DiscussionForum__c();
	private Boolean showWidget = false;
	private Id idProfile;
	private String IdAct = '';
	private Boolean already = false;

	// Get Team Id Attribute
	public String team;
	public List<DiscussionMember__c> membersToInsert = new List<DiscussionMember__c>();
	public List<User> mailList = new List<User>();
	public Integer groupCount = 1;	
	public String discussionName = null;
	public Member newMemberVars = new Member();
	public Boolean isAdministrator;
	//bool to send alert e-mail to added members
	public Boolean emailNotifications = false;
	//New save
	public Integer countSaved = 0;
	public Boolean reset = false;
	public List<DiscussionMember__c> memberListToolkit = new List<DiscussionMember__c>();
	public Integer memberListToolkitCount = 0;
	public Boolean errNotAllUsersAdded = false;
	public Boolean finishedAdding = false;
	
    // Sharing rules
	public UserPermissions userPermissionsI = new UserPermissions();
	
	/**
	* Constructor
	*/
	public DiscussionMembersWidgetController(){
		
		IdAct = system.currentPageReference().getParameters().get( 'id' );
		if( IdAct != null ){
			discussion = [ SELECT Id, Name, CreatedById FROM DiscussionForum__c WHERE Id =: IdAct ];
		}
		genPermissions();
	}	
	
	/**
	*@param b send email notifys
	*/
	public void setEmailNotifications(Boolean b)
	{
		emailNotifications = b;
	}
	
	/**
	*@return send email notifys
	*/
	public Boolean getEmailNotifications(){
		return emailNotifications;
	}
	
	/**
	*@param Boolean admnistrator profile condition
	*/
	public void setIsAdministrator( Boolean op ){
		isAdministrator = op;
	}
	
	/**
	*@return bool is admin
	*/
	public Boolean getIsAdministrator(){
		return isAdministrator;
	}
	
	/**
	*@return Boolean
	*/
	public Boolean getShowWidget(){
		return showWidget;
	}	
	
	/**
	*Set Boolean showWidget
	*/
	public void setShowWidget( Boolean param ){
		showWidget = param;
	}
	
	/**
	* Return the Namespace Prefix
	*@return String
	*/
	public String getNamespace () {
        return TeamUtil.getNamespace();
    } 
	
	/**
	* Return component title
	*@return String
	*/
	public String getComponentHeader () {
		return 'Discussion Members';	
	}

	/**
	* Return conditional for LinkAction
	*@return Boolean
	*/
	public Boolean getRenderLinkAction () {
		return true;
	}
	
	/**
	*@return String idUser
	*/
	public String getCurrentUser () {
		return UserInfo.getUserId();	
	}
	
	/**
	*@return actual DiscussionForum__c object
	*/
	public DiscussionForum__c getDiscussion(){
		return discussion;
	}

	public void getIsTeamAdmin(){}	
	
	/**
	* Get Team Members
	*@return List<DiscussionMember>
	*/
	public List<DiscussionMember__c> getMembers() {
		List<DiscussionMember__c> membersList = [ SELECT Id, User__r.Name, DiscussionProfile__r.Name FROM DiscussionMember__c WHERE DiscussionForum__c =: discussion.Id ORDER BY User__r.Name ];
		return membersList;
    }
    
    /**
    * Returns a String with Ids of the team
    *@return String
    */
    public String getDiscussionspaceMembersIds(){
    	String ret = '';
    	List<DiscussionMember__c> l = getMembers();
    	for(DiscussionMember__c tm: l){
    		ret += tm.id + '-';	
    	}
    	return ret;
    } 
	
	/**
	* Get Team Name
	*@return String discussion name
	*/
	public String getDiscussionName () {
		return discussion.Name;
	}
	
	/**
	*@return String
	*/
	public String getDiscussionId () { 
		return discussion.id;	
	}
	
	/**
	*@return List<SelectOption>
	*/
	public List<SelectOption> getProfilesOptions () {
		List<SelectOption> options = new List<SelectOption>();
		for (DiscussionProfile__c item: [ SELECT Id, Name FROM DiscussionProfile__c ORDER BY Name ]) {
			options.add(new SelectOption( item.Id,item.Name ));
		}
		return options;
	}
		
	/**
	* Assign new Member vars to new Profile
	*@void
	*/
	public void assignNewMemberVarsNewProfile () {
		List<DiscussionForum__c> currentDiscussion = [ SELECT NewMemberProfile__c FROM DiscussionForum__c WHERE id=: discussion.Id ];
		if (currentDiscussion.size() > 0 && currentDiscussion[0].NewMemberProfile__c != null) {	
			newMemberVars.profileId = currentDiscussion[0].NewMemberProfile__c;
		}
	}
	
	/**
	*@return Member
	*/	
	public Member getNewMemberVars () {
		return newMemberVars;	
	}
	
	/**
	*@param Member vars
	*/
	public void setNewMemberVars (Member vars) {
		this.newMemberVars = vars;
	}	
	
	/**
	*@return List<DiscussionMember__c>
	*/
	public List<DiscussionMember__c> getMemberListToolkit () {
		return memberListToolkit;
	}	
	
	/**
	*@return Integer
	*/
	public Integer getMemberListToolkitCount () {
		return memberListToolkitCount;
	}	
	
	/**
	*@return already exist
	*/
	public Boolean getAlready(){
		return already;
	}	
		
	public Boolean getErrNotAllUsersAdded() {
		return errNotAllUsersAdded;
	}
	
	public Boolean getFinishedAdding() {
		return finishedAdding;
	}
	
	/**
	* Save Members
	*@void
	*/
	public void saveMembers () {
		
		List<DiscussionMember__c> newMemberList = new List<DiscussionMember__c>();

		List<String> newMembers = newMemberVars.colleagueNames.split('[ ]*,[ ]*');
		
		List<User> userList = new List<User>();
		Set<String> alreadyList = new Set<String>(); 
		
		already = false;
		finishedAdding = false;
		errNotAllUsersAdded = false;
		
		Map<String, User> usersMap = new Map<String, User>();
		
		for (User iterUser :[select id, Name, IsActive, Email from User where Name in:newMembers]) {
			usersMap.put(iterUser.Name, iterUser);
		}
		
  		if (usersMap.size() != newMembers.size())
        	errNotAllUsersAdded = true;
        
        if ((newMembers.size()==0)){
        	errNotAllUsersAdded = true;
        	finishedAdding = true;
        }else{
        			
				for(String item: newMembers) {
					if (usersMap.get(item) != null && !alreadyList.contains(item)) {
						userList.add(usersMap.get(item));
						alreadyList.add(item);
					}
				}
				
				Map<Id, DiscussionMember__c> DiscussionMemberMap = new Map<Id, DiscussionMember__c>();
				for (DiscussionMember__c iterMember : [select id, User__c  from DiscussionMember__c where DiscussionForum__c =:discussion.id]) {
					DiscussionMemberMap.put(iterMember.User__c, iterMember);
				}
		
				for (User user : userList) {
					if (DiscussionMemberMap.get(user.Id) == null && usersMap.get(user.Name).IsActive != false) {
						DiscussionMember__c newMember = new DiscussionMember__c();
						newMember.User__c = user.id;
						newMember.Name = user.Name;
						newMember.DiscussionForum__c = discussion.id;
						
						if( isAdministrator )
							idProfile = [ SELECT Id FROM DiscussionProfile__c WHERE Name = 'DiscussionForum Administrator' ].id;
						else{
							List<DiscussionProfile__c> profileIdList = new List<DiscussionProfile__c>();
							profileIdList = [ SELECT id FROM DiscussionProfile__c WHERE Name =: 'Member Profile' ]; 
							if (profileIdList != null) { 
								idProfile =  profileIdList[0].id;
							}
						}
						newMember.DiscussionProfile__c = idProfile;
					
						newMemberList.add(newMember);
						if(emailNotifications)
							mailList.add(user);
					}
				}
				
				userList.clear();
				DiscussionMemberMap.clear();
				usersMap.clear();
				
				memberListToolkit = newMemberList;
				System.debug( '#####newMemberList: ' + newMemberList.size() );
				
				memberListToolkitCount = newMemberList.size();
				membersToInsert = newMemberList;
				newMemberVars.colleagueNames = '';
				newMemberVars.profileId = '';
				newMemberVars.message = '';
				
				finishedAdding = true;
        }
	}
	
	
	/**
	* Sync Save Members
	*@return PageReferenceb
	*/
	public PageReference syncSaveMembers(){
		
		Integer endIt =  countSaved + 2;
		for(Integer it = countSaved; it <= endIt; it++){
			if(it < membersToInsert.size()){
				DiscussionMember__c tm = membersToInsert[it];
				for(User user: mailList){
					if(tm.User__c == user.id){
						SendMail(user, newMemberVars.message);
					}
				}
				System.debug( '<*><*>' + 'it' + it + 'membersToInsert' +membersToInsert.size());
				insert tm;
				memberListToolkitCount--;
			}else{
				membersToInsert.clear();
				mailList.clear();
				groupCount = 0;
				reset = true;
			}
		}
		if(reset){
			countSaved = 0;
			reset = false;
		}else{
			countSaved += 3;
		}
		return null;
	}
	
	/**
	* Init save members
	*@return Boolean
	*/
	public Boolean getInitAddMembers (){
		System.debug( '(*)(*)' + (membersToInsert.size() > 0) );
		
		return ( membersToInsert.size() > 0 );
	} 
	
	/**
	* Send mail to new mambers
	*@void
	*/
	public void SendMail(User user, String message) {
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
       
        String[] toAddresses = new String[] {user.Email};
 		// Assign the addresses for the To and CC lists to the mail object.
		mail.setToAddresses(toAddresses);
		
		mail.setCharset('ISO-2022-JP');
		// Specify the address used when the recipients reply to the email.
		mail.setReplyTo('forwardtosfdc@gmail.com');
		// Specify the name used as the display name.
		mail.setSenderDisplayName(user.Name);
		// Specify the subject line for your email address.
		mail.setSubject('あなたは' + this.getDiscussionName() + 'フォーラムに登録されました');
		// Set to True if you want to BCC yourself on the email.
		mail.setBccSender(false);
		// Optionally append the salesforce.com email signature to the email.
		// The email address of the user executing the Apex Code will be used.
		mail.setUseSignature(true);
		// Specify the html version of the content as well.
		message = (message == null) ? '' : message;
		mail.setHtmlBody(message);
		// Send the email you have created.
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }	
    
	
	/**
	* Generate user permissions
	*/
	public void genPermissions() {
		userPermissionsI.setId(UserInfo.getUserId());
		System.debug('IId : ' + idAct );
		userPermissionsI.setTeam( idAct );
		userPermissionsI.setObjectType('DiscussionForum');
		userPermissionsI.setPermissions();		
	}
	
	/**
	* Return user permissions
	*@return UserPermissions
	*/
	public UserPermissions getUserPermissions () {
		return userPermissionsI;
	}	
	
	
	/**
	* Tell if the user can edit
	* @return Boolean
	*/
	public Boolean getCanEdit() {
		Boolean isOwner = (discussion.CreatedById == getCurrentUser());
		return ( getUserPermissions().getCanManage() || UserPermissions.getCanManageStatic() || isOwner);	
	}
	
	/**
	* Rerender use only
	*/
	public void refreshMethod(){}

	/**
	*@class
	*/
	public class Member {
		String profileId;
		String message;		
		String colleagueNames;
		
		/**
        *@return String
        */
		public String getColleagueNames () {
			return colleagueNames;
		}
		
		/**
        *@param String names
        */
		public void setColleagueNames (String names) {
			this.colleagueNames = names;
		}
		/**
        *@return String Message
        */
		public String getMessage () {
			return message;
		}
		
		/**
        *@param String Message
        */
		public void setMessage (String msj) {
			this.message = msj;
		}
		
		/**
        *@return String ID
        */
		public String getProfileId () {
			return profileId;
		}
		
		/**
        *@param String ID
        */
		public void setProfileId (String profile) {
			this.profileId = profile;
		}	
		
	}

}